import axios from "axios";

class MyAxios {
    instance;
    interceptors;
    constructor(config) {
        this.instance = axios.create(config);
        this.interceptors = config?.interceptors;

        // 使用实例拦截器
        this.instance.interceptors.request.use(
            this.interceptors?.requestInterceptor,
            this.interceptors?.requestInterceptorCatch
        );

        this.instance.interceptors.response.use(
            this.interceptors?.responseInterceptor,
            this.interceptors?.responseInterceptorCatch
        );
    }

      // extraConfig 暂时不做处理 -- > 预留
  request(config, extraConfig) {
    return new Promise((resolve, reject) => {
        // 接口单独传递的请求拦截器 对config处理
        if (config.interceptors?.requestInterceptor) {
          config = config.interceptors.requestInterceptor(config)
        }

        this.instance
          .request(config)
          .then((res) => {
            // 接口单独传递的响应拦截器 对res处理
            if (config.interceptors?.responseInterceptor) {
              res = config.interceptors.responseInterceptor(res)
            }
            resolve(res.data)
          })
          .catch((err) => {
            if (config.interceptors?.responseInterceptorCatch) {
              err = config.interceptors.responseInterceptorCatch(err)
            }
            reject(err.response?.data)
          })
      })
  }
}

export default MyAxios
